package com.epam.debrecen.hackathon;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.epam.debrecen.hackathon.ai.Bot;
import com.epam.debrecen.hackathon.ai.model.Region;
import com.epam.debrecen.hackathon.ai.model.Regions;
import com.epam.debrecen.hackathon.net.BotServer;

public class Main {

	public static final boolean DEBUG = true;

	private static final boolean LOCAL = false;

	public static void main(String[] args) throws IOException {

		if (!Main.LOCAL) {
			new Main().start("startup-info");
		} else {

			ExecutorService executor = Executors.newFixedThreadPool(2);

			executor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						new Main().start("startup-info_blue");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});

			executor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(1000);
						new Main().start("startup-info_red");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});

		}

	}

	private void start(String fileName) throws NumberFormatException, UnknownHostException, IOException {

		Scanner scanner = this.getScanner(fileName);

		String host = scanner.next();
		String pass = scanner.next();

		System.out.println(String.format("Client has started with. Host: %s, Pass:%s", host, pass));

		Bot bot = new Bot(this.initRegions());

		new BotServer(pass, host, bot).start();

	}

	private Regions initRegions() throws IOException {
		Properties props = new Properties();

		Regions regions = new Regions();

		try {
			props.load(Main.class.getClassLoader().getResourceAsStream("regionProps.txt"));

			Iterator<Object> iterator = props.keySet().iterator();

			while (iterator.hasNext()) {
				Region region = new Region(iterator.next().toString());

				regions.addRegion(region);

				String[] split = props.getProperty(region.getName()).split(",");
				for (String neighbour : split) {
					regions.addNeighbour(region.getName(), new Region(neighbour));
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}

		System.out.println(regions.getRegionList());
		return regions;

	}

	private Scanner getScanner(String fileName) {
		Scanner scanner = null;

		try {
			scanner = new Scanner(new File(fileName));
		} catch (Exception e) {
		}

		try {
			scanner = new Scanner(this.getClass().getResourceAsStream("/" + fileName));
		} catch (Exception e) {
		}

		return scanner;
	}
}
